package com.cavy.platform.server.validator;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.repository.WorkSpaceRepository;
import org.eclipse.jgit.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * author: 唐旭
 */
public class WorkSpaceNotRepeatValidator implements ConstraintValidator<WorkSpaceNotRepeat, String> {
    private WorkSpaceRepository repository;
    @Override
    public void initialize(WorkSpaceNotRepeat workSpaceNotRepeat) {
        repository = BeansProvider.getBean(WorkSpaceRepository.class);
    }

    @Override
    public boolean isValid(String name, ConstraintValidatorContext context) {
        if (StringUtils.isEmptyOrNull(name)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("工作空间名称不能为空").addConstraintViolation();
            return false;
        }

        assert repository != null;
        int count = repository.countByName(name);
        if (count > 0) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("已经存在该名称的工作空间").addConstraintViolation();
            return false;
        }
        return true;
    }
}
